<template>
  <div style="height: 300px; width: 100%">
    <vue3-tree-org
      v-if="treeData"
      style="background-color: #eff2f5"
      :data="treeData"
      :horizontal="true"
      :collapsable="true"
      :label-style="{ background: '#fff', color: '#5e6d82' }"
      :node-draggable="false"
      :scalable="true"
      :only-one-node="true"
      :default-expand-level="9"
      :clone-node-drag="true"
      :define-menus="[]"
    >
      <template v-slot="{ node }">
        <div v-if="node.$$data.type == 'start'">
          <el-input style="width: 100px" disabled v-model="node.$$data.value" class="mw" />
        </div>
        <div v-if="node.$$data.type == 'field'" class="flex" style="background-color: #eff2f5">
          <div v-if="node.$$data.connect" style="width: 50px; height: 30px; line-height: 30px">
            <div>{{ node.$$data.connect }}</div>
          </div>
          <el-select
            v-model="node.$$data.value"
            style="width: 200px"
            filterable
            placeholder="请选择"
            @change="valueChange($event, node)"
          >
            <template #prefix>字段：</template>
            <el-option
              v-for="item in fieldList"
              :key="item.COLUMN_NAME"
              :label="`${item.COLUMN_NAME} ${item.chName ? '(' + item.chName + ')' : ''}`"
              :value="item.COLUMN_NAME"
            />
          </el-select>
          <el-select v-model="node.$$data.compare" filterable placeholder="请选择" style="width: 200px" class="ml-4">
            <template #prefix>符号：</template>
            <el-option label=">" value=">" />
            <el-option label=">=" value=">=" />
            <el-option label="<" value="<" />
            <el-option label="<=" value="<=" />
            <el-option label="=" value="=" />
            <el-option label="!=" value="!=" />
            <el-option label="like" value="like" />
            <el-option label="isNull" value="isNull" />
            <el-option label="notNull" value="notNull" />
            <el-option label="startsWith" value="startsWith" />
            <el-option label="endsWith" value="endsWith" />
            <el-option label="in" value="in" />
          </el-select>
          <el-select
            v-if="node.$$data.compare != 'isNull' && node.$$data.compare != 'notNull'"
            v-model="node.$$data.compareType"
            filterable
            placeholder="请选择"
            style="width: 200px"
            class="ml-4"
          >
            <template #prefix>类型：</template>
            <!-- <el-option label="字段" value="field" /> -->
            <el-option label="值" value="value" />
            <el-option label="时间" value="date" />
          </el-select>
          <el-select
            v-if="
              node.$$data.compareType == 'field' && node.$$data.compare != 'isNull' && node.$$data.compare != 'notNull'
            "
            v-model="node.$$data.compareField"
            style="width: 200px"
            class="ml-4"
            filterable
            placeholder="请选择"
            @change="compareFieldChange($event, node)"
          >
            <template #prefix>字段：</template>
            <el-option
              v-for="item in fieldList"
              :key="item.COLUMN_NAME"
              :label="`${item.COLUMN_NAME} ${item.chName ? '(' + item.chName + ')' : ''}`"
              :value="item.COLUMN_NAME"
            />
          </el-select>
          <el-input
            v-if="
              node.$$data.compareType == 'value' && node.$$data.compare != 'isNull' && node.$$data.compare != 'notNull'
            "
            :type="node.$$data.compare == 'in' ? 'textarea' : 'text'"
            :autosize="{ minRows: 1, maxRows: 2 }"
            style="width: 200px"
            class="ml-4"
            v-model="node.$$data.compareValue"
            placeholder="请输入"
          >
            <template #prefix>值：</template>
          </el-input>
          <el-date-picker
            v-if="node.$$data.compareType == 'date'"
            style="width: 200px"
            class="ml-4"
            v-model="node.$$data.compareValue"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请输入"
          >
            <template #prefix>值：</template>
          </el-date-picker>
          <div class="close" style="width: 60px">
            <el-tooltip content="复制" placement="top">
              <el-icon color="#67C23A" v-if="node.pid != 1" style="cursor: pointer" @click="handleCopy(node)">
                <Connection />
              </el-icon>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-icon color="red" style="cursor: pointer; margin-left: 10px" @click="handleDel(node)">
                <CircleClose />
              </el-icon>
            </el-tooltip>
          </div>
        </div>
        <div v-if="node.$$data.type == 'condition'" class="flex" style="background-color: #eff2f5">
          <el-select v-model="node.$$data.condition" style="width: 200px" placeholder="请选择">
            <template #prefix>条件：</template>
            <el-option label="AND" value="AND" />
            <el-option label="OR" value="OR" />
          </el-select>
          <div class="close">
            <el-icon color="red" style="cursor: pointer" @click="handleDel(node)"><CircleClose /></el-icon>
          </div>
        </div>
        <div v-if="node.$$data.type == 'btn'" style="background-color: #eef2f5; width: 200px">
          <!-- <el-button type="primary" @click="handleAddAnd">添加AND</el-button> -->
          <!-- <el-button type="primary" @click="handleAddOr">添加OR</el-button> -->
          <el-button
            :disabled="node.$$data.id == 999 && treeData.children[0].type != 'btn'"
            :type="node.$$data.id == 999 && treeData.children[0].type != 'btn' ? 'info' : 'primary'"
            @click="handleAddCondition(node)"
          >
            添加条件
          </el-button>
          <el-button
            :disabled="node.$$data.id == 999 && treeData.children[0].type != 'btn'"
            :type="node.$$data.id == 999 && treeData.children[0].type != 'btn' ? 'info' : 'primary'"
            @click="handleAddRule(node)"
          >
            添加规则
          </el-button>
        </div>
      </template>
    </vue3-tree-org>
  </div>
</template>

<script setup>
import { onMounted, ref, watch } from 'vue-demi'
import { CircleClose, Connection } from '@element-plus/icons-vue'

const treeData = ref([])
const props = defineProps({
  fieldList: {
    type: Array,
    default: () => []
  },
  data: {
    type: Object
  }
})
onMounted(() => {
  console.log(props.data)
  if (props.data?.id) {
    treeData.value = props.data
  } else {
    treeData.value = {
      id: 1,
      type: 'start',
      pid: 0,
      value: '开始',
      children: [
        {
          id: 999,
          type: 'btn',
          pid: 1
        }
      ]
    }
  }
})
const handleAddAnd = () => {
  treeData.value.children.splice(treeData.value.children.length - 1, 0, {
    id: new Date().getTime(),
    type: 'field',
    connect: 'AND',
    pid: 1
  })
}
const handleAddOr = () => {
  treeData.value.children.splice(treeData.value.children.length - 1, 0, {
    id: new Date().getTime(),
    type: 'field',
    connect: 'OR',
    pid: 1
  })
}
const handleAddCondition = (node) => {
  console.log(node)
  if (node.pid == 1) {
    const id = new Date().getTime()
    treeData.value.children.splice(treeData.value.children.length - 1, 0, {
      id,
      type: 'condition',
      pid: 1,
      children: [
        {
          id: id + 'btn',
          type: 'btn',
          pid: id
        }
      ]
    })
  } else {
    let pnode = getPNode(treeData.value, node)
    console.log(pnode)
    const id = new Date().getTime()
    pnode.children.splice(pnode.children.length - 1, 0, {
      id,
      type: 'condition',
      pid: pnode.id,
      children: [
        {
          id: id + 'btn',
          type: 'btn',
          pid: id
        }
      ]
    })
  }
}
const handleAddRule = (node) => {
  console.log(node)
  if (node.pid == 1) {
    treeData.value.children.splice(treeData.value.children.length - 1, 0, {
      id: new Date().getTime(),
      type: 'field',
      pid: 1
    })
  } else {
    let pnode = getPNode(treeData.value, node)
    console.log(pnode)
    pnode.children.splice(pnode.children.length - 1, 0, {
      id: new Date().getTime(),
      type: 'field',
      pid: pnode.id
    })
  }
}
const getPNode = (nodes, node) => {
  let pnode = ''
  for (let i = 0; i < nodes.children.length; i++) {
    console.log(nodes.children[i].id, node.pid)
    if (nodes.children[i].id == node.pid) {
      pnode = nodes.children[i]
      break
    }
    if (nodes.children[i].children && nodes.children[i].children.length > 0) {
      pnode = getPNode(nodes.children[i], node)
      break
    }
  }
  // nodes.children.forEach((item) => {
  //   if (item.id == node.pid) {
  //     pnode = item
  //   }
  //   if (item.children && item.children.length > 0) {
  //     getPNode(item, node)
  //   }
  // })
  return pnode
}
const handleDel = (node) => {
  console.log(node)
  if (node.pid == 1) {
    treeData.value.children.splice(
      treeData.value.children.findIndex((item) => item.id == node.id),
      1
    )
  } else {
    let pnode = getPNode(treeData.value, node)
    console.log(pnode)
    pnode.children.splice(
      pnode.children.findIndex((item) => item.id == node.id),
      1
    )
  }
}
const handleCopy = (node) => {
  if (node.pid == 1) {
    return
  } else {
    let pnode = getPNode(treeData.value, node)
    console.log(pnode)
    pnode.children.splice(pnode.children.length - 1, 0, {
      ...node.$$data,
      id: new Date().getTime()
    })
  }
}
const valueChange = (e, node) => {
  console.log(node)
  const chose = props.fieldList.find((item) => item.COLUMN_NAME == node.$$data.value)
  node.$$data.chName = chose.chName
}
const compareFieldChange = (e, node) => {
  console.log(node)
  const chose = props.fieldList.find((item) => item.COLUMN_NAME == node.$$data.compareField)
  node.$$data.compareChName = chose.chName
}
defineExpose({
  treeData
})
</script>

<style lang="scss" scoped>
.close {
  width: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
